package com.platform.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.platform.dao.AddressDao;
import com.platform.dao.OrderDao;
import com.platform.entity.AddressEntity;
import com.platform.entity.OrderEntity;

/**
 * Service接口
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-16 17:22:46
 */
@Service("addressService")
public class AddressService {
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private OrderDao orderDao;

    public AddressEntity queryObject(Integer id) {
        return addressDao.queryObject(id);
    }

    public List<AddressEntity> queryList(Map<String, Object> map) {
        List<AddressEntity> list = addressDao.queryList(map);
        if (null != list && list.size() > 0) {
//            for (AddressEntity addressEntity : list) {
//                //翻译收货地址国家码
//
//            }
        }
        return list;
    }

    public int queryTotal(Map<String, Object> map) {
        return addressDao.queryTotal(map);
    }

    @Transactional
    public int save(AddressEntity address) {
    	if(address.getIsdefault() == 1) {
    		addressDao.resetAllNoDefault(address.getUserId());
    	}
    	if(address.getId()==null) {
            return addressDao.save(address);
    	}else {
            return addressDao.update(address);
    	}
    }

    @Transactional
    public int update(AddressEntity address) {
    	if(address.getIsdefault() == 1) {
    		addressDao.resetAllNoDefault(address.getUserId());
    	}
    	
        return addressDao.update(address);
    }

    public int delete(Integer id) {
        return addressDao.delete(id);
    }

    public int deleteBatch(Integer[] ids) {
        return addressDao.deleteBatch(ids);
    }
    
    
    @Transactional
    public int setDefault(Integer id,Integer userId){
		addressDao.resetAllNoDefault(userId);
        return addressDao.setDefault(id);
    }
    
    @Transactional
    public void saveAddToOrder(AddressEntity address,Integer orderId) {
    	if(address.getIsdefault() == 1) {
    		addressDao.resetAllNoDefault(address.getUserId());
    	}
    	if(address.getId()==null) {
            addressDao.save(address);
    	}else {
            addressDao.update(address);
    	}
    	OrderEntity orderInfo = orderDao.queryObject(orderId);
	      //收货地址和运费
	      orderInfo.setConsignee(address.getUserName());
	      orderInfo.setMobile(address.getTelNumber());
	      orderInfo.setCountry(address.getNationalCode());
	      orderInfo.setProvince(address.getProvinceName());	
	      orderInfo.setCity(address.getCityName());
	      orderInfo.setDistrict(address.getCountyName());
	      orderInfo.setAddress(address.getDetailInfo());
	      orderInfo.setAddressId(address.getId());
	      orderDao.update(orderInfo);
    }

}
